package com.example.product.controller;

import com.example.product.model.Product;
import com.example.product.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/products")
public class ProductController {

    @Autowired
    private ProductMapper productMapper;

    @GetMapping
    public List<Product> getAllProducts() {
        return productMapper.findAll();
    }

    @PostMapping
    public Product createProduct(@RequestBody Product product) {
        productMapper.save(product);
        return product;
    }

    @PutMapping("/{id}")
    public ResponseEntity<Product> updateProduct(@PathVariable Long id, @RequestBody Product product) {
        Product existingProduct = productMapper.findById(id);
        if (existingProduct != null) {
            product.setId(id);
            productMapper.update(product);
            return ResponseEntity.ok(product);
        }
        return ResponseEntity.notFound().build();
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteProduct(@PathVariable Long id) {
        Product product = productMapper.findById(id);
        if (product != null) {
            productMapper.deleteById(id);
            return ResponseEntity.ok().build();
        }
        return ResponseEntity.notFound().build();
    }

    @GetMapping("/TEST")
    public ResponseEntity<?> TEST() {
        return ResponseEntity.ok("xxxxx");
    }
}
